package com.itheima.web.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Freeze;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.FreezeService;
import com.itheima.service.db.UserInfoService;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class FreezeJob {

    @DubboReference
    private FreezeService freezeService;

    @DubboReference
    private UserInfoService userInfoService;

    /**
     * 自动解冻定时任务, 每天凌晨0点执行
     */
    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "0/30 * * * * ?")
    public void unFreezeJob(){
        //准备基础数据
        String threeDayAgo = DateUtil.offsetDay(new Date(),-3).toDateStr();
        String lastWeek = DateUtil.offsetDay(new Date(),-7).toDateStr();

        //查询所有状态冻结(排除永久冻结)的数据
        List<Freeze> freezeList = freezeService.findAllFreeze();

        System.out.println("自动执行解冻任务,对象:" + freezeList);

        //判断是否为空
        if (CollectionUtil.isNotEmpty(freezeList)) {
            //不会空,进行遍历
            freezeList.forEach(e -> {
                //获取冻结时间freezingTime类型
                Integer timeType = e.getFreezingTime();
                switch (timeType) {
                    case 1:{
                        String created = DateUtil.formatDate(e.getCreated());
                        if (Objects.equals(created,threeDayAgo)) {//对比时间是否相等
                            unFreezeAndUpdateUser(e);//相等,进行解冻操作,原因为自动解冻
                        }
                        break;
                    }
                    case 2:{
                        String created = DateUtil.formatDate(e.getCreated());
                        if (Objects.equals(created,lastWeek)) {
                            unFreezeAndUpdateUser(e);
                        }
                        break;
                    }
                }
            });

        }
    }

    private void unFreezeAndUpdateUser(Freeze e) {
        e.setDeleted(1);
        e.setReasonsForThawing("到时自动");
        freezeService.update(e);

        //更新用户信息
        UserInfo userInfo = userInfoService.findByUserId(Long.valueOf(e.getUserId()));
        userInfo.setUserStatus("1");
        userInfoService.update(userInfo);
    }
}
